package com.test.common.utils;

import com.test.common.response.BizException;
import com.test.common.ProcessInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

@Slf4j
public class FileUploadUtils {

    public static List<FileItem> fileUpload(HttpServletRequest request, String uploadId) {

        try {
            final HttpSession hs = request.getSession();

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (!isMultipart) {
                return Collections.emptyList();
            }

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");

            upload.setProgressListener((pBytesRead, pContentLength, pItems) -> {

                ProcessInfo processInfo = new ProcessInfo();

                processInfo.setItemNum(pItems);
                processInfo.setReadSizeMB(pBytesRead / 1024.0 / 1024.0);
                processInfo.setTotalSizeMB(pContentLength / 1024.0 / 1024.0);
                processInfo.updatePercent();

                hs.setAttribute(uploadId, processInfo);
            });

            List<FileItem> items = upload.parseRequest(request);
            if (items.isEmpty()) {
                return Collections.emptyList();
            } else {
                return items;
            }
        } catch (Exception e) {
            log.error("上传文件异常");
            e.printStackTrace();
            throw new BizException("上传文件异常", e);
        }
    }

    public static ProcessInfo uploadProcess(HttpServletRequest request, String uploadId) {
        try {
            ProcessInfo processInfo = (ProcessInfo) request.getSession().getAttribute(uploadId);

            if (processInfo != null) {
                return processInfo;
            } else {
                throw new BizException("没有查询到相关进度：" + uploadId);
            }
        } catch (Exception e) {
            log.error("查询进度异常：{}", e.getMessage());
            e.printStackTrace();
            throw new BizException("查询进度异常", e);
        }
    }

    public static String clearProcess(HttpServletRequest request, String uploadId) {

        try {
            request.getSession().removeAttribute(uploadId);
            return "释放进度信息成功";
        } catch (Exception e) {
            log.error("释放进度信息异常：{}", e.getMessage());
            e.printStackTrace();
            throw new BizException("释放进度信息异常", e);
        }
    }
}
